package org.dromara.one.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class SqlFileUtil {

    @Value("${sqlFileUrl}")
    private String sqlFileUrl;

    @Value("${sqlFileName}")
    private String sqlFileName;
    private static final long fileSize = 5000;
    private final LogFileConfig LogFileConfig;

    /**
     * 保存信息到文件
     * @param dateStr
     * @param type
     */
    public void setFileData(String dateStr, String type){
        try {
            String fileName = type + "_" + sqlFileName + "_" + UUID.fastUUID().toString(true) + ".txt";
            String url = LogFileConfig.init(sqlFileUrl,fileName);
            LogFileConfig.saveLock(url,dateStr);
        }catch (Exception ex){
            log.info("--------信息写入文件异常：{}---------文件类型：{}-------",dateStr,type);
            ex.printStackTrace();
        }
    }
    /**
     * @param type 文件信息 类型
     * @return
     */
    public List<String> getFileData(String type, Boolean isCopy){
        List<String> fileDateList = new ArrayList<>();
        LogFileConfig.getFileData(fileDateList,sqlFileUrl,sqlFileName,type,fileSize,isCopy);
        return fileDateList;
    }
    private void copyFile(File file, String de, String deName){
        File tempFile = new File(de);
        de += UUID.fastUUID().toString(true) + "_" + deName;
        if (!tempFile.exists()){
            tempFile.mkdir();
        }
        FileUtil.copy(file.getAbsolutePath(),de, false);
    }

    /**
     * 清除文件
     * @param tempFileList 文件地址
     * @param isCopy 是否备份
     */
    @Async
    public void delFile(List<File> tempFileList,Boolean isCopy){
        for (File file1 : tempFileList) {
            if (!file1.exists()){
                continue;
            }
            if(isCopy){
                copyFile(file1,sqlFileUrl + "\\delete\\",file1.getName());
            }
            FileUtil.del(file1.getAbsolutePath());
        }
    }

}
